package com.njit.postbar;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Looper;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.njit.postbar.model.MailCode;
import com.njit.postbar.model.User;
import com.njit.postbar.utils.MD5;
import com.njit.postbar.utils.Remove;
import com.njit.postbar.utils.SendCode;
import com.sun.mail.util.MailConnectException;

import org.litepal.LitePal;

import java.util.List;
import java.util.Random;

import javax.mail.MessagingException;

import static com.njit.postbar.utils.Check.checkEmail;
import static com.njit.postbar.utils.Check.checkPhone;

public class SignUp extends Activity {

    private EditText email;
    private EditText password;
    private EditText phone;
    private EditText codeView;

    private Button signUpButton;
    private Button getCodeButton;
    private Button backToLogin;

    private MailCode mailCode;

    private ImageView []bubble;
    private ImageView clearEmail;
    private ImageView clearPhone;
    private ImageView seePWD;

    private View background;
    private TextView tip;

    private Thread [] threads;

    private MediaPlayer [] player;
    private boolean flag = true;
    private boolean isShow = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.signup);
        Remove.removeTop(this);
        //文本框
        email = findViewById(R.id.signUp_email_text);
        password = findViewById(R.id.signUp_password_text);
        phone = findViewById(R.id.phone);
        codeView = findViewById(R.id.signUp_code_text);
        //按钮
        signUpButton = findViewById(R.id.signUp_confirm);
        getCodeButton = findViewById(R.id.get_code);
        backToLogin = findViewById(R.id.back_to_login);
        tip = findViewById(R.id.please_clear);
        clearEmail = findViewById(R.id.clear_email);
        clearPhone = findViewById(R.id.clear_phone);
        //背景
        background = findViewById(R.id.background);
        //五个动画线程
        threads = new Thread[5];
        //验证码和邮箱
        mailCode = new MailCode();
        //注册表格
        formEditListener();
        //获取邮箱验证码
        getCodeListener();
        //注册
        signUpListener();
        //开启动画线程
        animThread();
        //点击气泡三种音效
        touchListener();
        //从登录界面跳过来
        Intent intent = getIntent();
        String data = intent.getStringExtra("email");
        if(data!=null)
            email.setText(data);
    }


    /**
     *@author yuruiqiao
     *@date 2020/5/25
     *@description 判断邮箱是否被注册
     */
    public boolean emailUnique(){
        List<User> users_email = LitePal.where("email = ?",email.getText().toString()).find(User.class);
        if(users_email.size()>0){
            Toast.makeText(getBaseContext(),"邮箱已被注册", Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }


    /**
     *@author yuruiqiao
     *@date 2020/5/25
     *@description 判断机号是否被注册
     */
    public boolean phoneUnique(){
        List<User> users_phone = LitePal.where("phone = ?",phone.getText().toString()).find(User.class);
        if(users_phone.size()>0){
            Toast.makeText(getBaseContext(),"手机号已被注册", Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }


    /**
     *@author yuruiqiao
     *@date 2020/5/25
     *@description 基本信息验证
     */
    public boolean checkInfo(){
        if(!checkEmail(email.getText().toString())){
            Toast.makeText(getBaseContext(),"邮箱格式错误", Toast.LENGTH_LONG).show();
            return false;
        }

        if(password.getText().length()<6){
            Toast.makeText(getBaseContext(),"密码不少于6位", Toast.LENGTH_LONG).show();
            return false;
        }

        if(!codeView.getText().toString().equals(mailCode.getCode()+"")){
            Toast.makeText(getBaseContext(),"验证码错误", Toast.LENGTH_LONG).show();
            return false;
        }

        if(!email.getText().toString().equals(mailCode.getMailTo())){
            Toast.makeText(getBaseContext(),"邮箱与验证码不匹配", Toast.LENGTH_LONG).show();
            return false;
        }

        if(!checkPhone(phone.getText().toString())){
            Toast.makeText(getBaseContext(),"手机号格式错误", Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }


    /**
     *@author yuruiqiao
     *@date 2020/5/25
     *@description 获取邮箱验证码
     */
    public void getCodeListener(){
        getCodeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!checkEmail(email.getText().toString()))
                    Toast.makeText(getBaseContext(),"邮箱格式错误", Toast.LENGTH_LONG).show();
                else if(!emailUnique())
                    Toast.makeText(getBaseContext(),"邮箱已被注册", Toast.LENGTH_LONG).show();
                else{
                    //创建一个线程来发送邮箱
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            //生成六位验证码
                            mailCode.setCode((int)((Math.random()*9+1)*100000));
                            //验证码要和邮箱匹配
                            mailCode.setMailTo(email.getText().toString());
                            Looper.prepare();
                            try {
                                SendCode.send(email.getText().toString(), mailCode.getCode()+"");
                                getCodeButton.setVisibility(View.INVISIBLE);
                                tip.setVisibility(View.VISIBLE);
                                Toast.makeText(getBaseContext(),"验证码已发送", Toast.LENGTH_LONG).show();
                            } catch (MailConnectException me) {
                                Toast.makeText(getBaseContext(),"请检查网络连接", Toast.LENGTH_LONG).show();
                                me.printStackTrace();
                            } catch (MessagingException me){
                                Toast.makeText(getBaseContext(),"操作过于频繁", Toast.LENGTH_LONG).show();
                                me.printStackTrace();
                            } catch (Exception e){
                                Toast.makeText(getBaseContext(),"未知错误", Toast.LENGTH_LONG).show();
                                e.printStackTrace();
                            }
                            Looper.loop();
                        }
                    }).start();
                }
            }
        });
    }


    /**
     *@author yuruiqiao
     *@date 2020/5/25
     *@description 注册监听器
     */
    public void signUpListener(){
        signUpButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //此处进行判断是否被注册
                if(checkInfo() && emailUnique() && phoneUnique()){
                    User user = new User();
                    user.setEmail(email.getText().toString());
                    user.setPhone(phone.getText().toString());
                    //MD5加密
                    user.setPassword(MD5.getMD5String(password.getText().toString()));
                    //用户名默认邮箱,可以修改
                    user.setUserName(email.getText().toString());
                    //默认用户头像
                    user.setHeadImage("http://www.westudy.ltd/upload/default.png");
                    user.save();
                    Toast.makeText(getBaseContext(),"注册成功", Toast.LENGTH_LONG).show();
                    //结束动画线程
                    flag = false;
                    //跳转登录页面,传递对象
                    Intent intent = new Intent();
                    intent.setClass(SignUp.this,Login.class);
                    Bundle bundle = new Bundle();
                    //由于插入数据库的密码加密,这边传递要改回来
                    user.setPassword(password.getText().toString());
                    bundle.putSerializable("user", user);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    finish();
                }
            }
        });
    }


    /**
     *@author yuruiqiao
     *@date 2020/5/26
     *@description 动画函数
     */
    public AnimationSet animation(int left_start,int time,float size){
        int height = background.getHeight()/2+300;
        //位移动画
        TranslateAnimation ta = new TranslateAnimation(left_start, left_start, height, -1*height);
        //旋转动画
        RotateAnimation ra = new RotateAnimation(0, -90, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        //透明度变化
        AlphaAnimation aa = new AlphaAnimation(1, 0.3f);
        //缩放
        ScaleAnimation sa = new ScaleAnimation(size, size, size, size, ScaleAnimation.RELATIVE_TO_SELF, 1, ScaleAnimation.RELATIVE_TO_SELF, 1);
        //动画集合
        AnimationSet aSet = new AnimationSet(true);
        aSet.addAnimation(ra);
        aSet.addAnimation(ta);
        aSet.addAnimation(sa);
        aSet.addAnimation(aa);
        aSet.setDuration(time);
        aSet.setFillAfter(true);
        return aSet;
    }

    /**
     *@author yuruiqiao
     *@date 2020/5/26
     *@description 触屏出声音
     */
    public void touchListener(){
        player = new MediaPlayer[3];
        player[0] = MediaPlayer.create(SignUp.this,R.raw.yinxiao_1);
        player[1] = MediaPlayer.create(SignUp.this,R.raw.yinxiao_2);
        player[2] = MediaPlayer.create(SignUp.this,R.raw.yinxiao_3);
        //触屏事件
        background.setOnTouchListener(new View.OnTouchListener() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Random random = new Random();
                int num = random.nextInt(3);
                player[num].start();
                background.clearFocus();
                return false;
            }
        });
    }

    /**
     *@author yuruiqiao
     *@date 2020/5/26
     *@description 动画线程
     */
    public void animThread(){

        bubble = new ImageView[5];
        bubble[0] = findViewById(R.id.bubble1);
        bubble[1] = findViewById(R.id.bubble2);
        bubble[2] = findViewById(R.id.bubble3);
        bubble[3] = findViewById(R.id.bubble4);
        bubble[4] = findViewById(R.id.bubble5);

        threads[0] = new Thread(new Runnable() {
            @Override
            public void run() {
                circleAnim(bubble[0]);
            }
        });
        threads[0].start();
        threads[1] = new Thread(new Runnable() {
            @Override
            public void run() {
                circleAnim(bubble[1]);
            }
        });
        threads[1].start();
        threads[2] = new Thread(new Runnable() {
            @Override
            public void run() {
                circleAnim(bubble[2]);
            }
        });
        threads[2].start();
        threads[3] = new Thread(new Runnable() {
            @Override
            public void run() {
                circleAnim(bubble[3]);
            }
        });
        threads[3].start();
        threads[4] = new Thread(new Runnable() {
            @Override
            public void run() {
                circleAnim(bubble[4]);
            }
        });
        threads[4].start();
    }
    /**
     *@author yuruiqiao
     *@date 2020/5/26
     *@description 动画循环
     */
    public void circleAnim(ImageView view){
        while(flag){
            int time = (int)(Math.random()*10000)+3000;
            int left = (int)(Math.random()*1000)-500;
            float size = (float)Math.random()*0.6f+0.4f;
            view.startAnimation(animation(left,
                    time,size));
            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     *@author yuruiqiao
     *@date 2020/5/26
     *@description 注册的填写
     */
    public void formEditListener(){
        //清除邮箱
        clearEmail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                email.setText("");
                getCodeButton.setVisibility(View.VISIBLE);
                tip.setVisibility(View.INVISIBLE);
            }
        });
        //清除手机号
        clearPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phone.setText("");
            }
        });
        //密码可见
        seePWD = findViewById(R.id.see_signUp);
        seePWD.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //如果密码可见
                if(isShow){
                    //切换图标
                    seePWD.setBackground(getDrawable(R.drawable.ic_eye_close));
                    //设置密码不可见
                    password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
                    //改变状态值为假
                    isShow = false;
                }else{
                    //切换图标
                    seePWD.setBackground(getDrawable(R.drawable.ic_eye));
                    //设置密码可见
                    password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    //改变状态值为真
                    isShow = true;
                }
            }
        });
        //返回登录
        backToLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //结束动画线程
                flag = false;
                //跳转登录页面
                Intent intent = new Intent();
                intent.setClass(SignUp.this,Login.class);
                startActivity(intent);
                finish();
            }
        });
    }
}
